<template>
  <div class="popup-stats-tab">
    <!-- 统计概览卡片 -->
    <div class="stats-overview">
      <el-row :gutter="20">
        <el-col :span="6" v-for="stat in overviewStats" :key="stat.label">
          <el-card class="stat-card" shadow="hover">
            <div class="stat-content">
              <div class="stat-icon" :style="{ backgroundColor: stat.color }">
                <el-icon :size="24" color="white">
                  <component :is="stat.icon" />
                </el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-value">{{ stat.value }}</div>
                <div class="stat-label">{{ stat.label }}</div>
                <div class="stat-trend" v-if="stat.trend">
                  <span :class="stat.trend > 0 ? 'trend-up' : 'trend-down'">
                    {{ stat.trend > 0 ? '+' : '' }}{{ stat.trend }}%
                  </span>
                  <span class="trend-text">较上期</span>
                </div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 主要图表区域 -->
    <div class="main-charts">
      <el-row :gutter="20">
        <!-- 弹窗展示趋势图 -->
        <el-col :span="16">
          <el-card class="chart-card" shadow="hover">
            <template #header>
              <div class="chart-header">
                <span>弹窗展示趋势分析</span>
                <div class="chart-controls">
                  <el-radio-group v-model="trendPeriod" size="small" @change="updateTrendChart">
                    <el-radio-button label="7">近7天</el-radio-button>
                    <el-radio-button label="30">近30天</el-radio-button>
                    <el-radio-button label="90">近90天</el-radio-button>
                  </el-radio-group>
                </div>
              </div>
            </template>
            <div class="chart-container large">
              <v-chart class="chart" :option="lineChartOption" />
            </div>
          </el-card>
        </el-col>

        <!-- 转化率分析图 -->
        <el-col :span="8">
          <el-card class="chart-card" shadow="hover">
            <template #header>
              <div class="chart-header">
                <span>转化率分析</span>
              </div>
            </template>
            <div class="chart-container medium">
              <v-chart class="chart" :option="pieChartOption" />
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 详细统计图表 -->
    <div class="detail-charts">
      <el-row :gutter="20">
        <!-- 各站点表现对比 -->
        <el-col :span="12">
          <el-card class="chart-card" shadow="hover">
            <template #header>
              <div class="chart-header">
                <span>各站点弹窗表现对比</span>
                <el-select v-model="selectedPeriod" style="width: 120px;" size="small" @change="updateCharts">
                  <el-option label="本月" value="2024-01" />
                  <el-option label="上月" value="2023-12" />
                  <el-option label="本季度" value="2024-Q1" />
                </el-select>
              </div>
            </template>
            <div class="chart-container medium">
              <v-chart class="chart" :option="barChartOption" />
            </div>
          </el-card>
        </el-col>

        <!-- 用户行为漏斗图 -->
        <el-col :span="12">
          <el-card class="chart-card" shadow="hover">
            <template #header>
              <div class="chart-header">
                <span>用户行为漏斗</span>
              </div>
            </template>
            <div class="chart-container medium">
              <v-chart class="chart" :option="funnelChartOption" />
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 数据筛选和操作 -->
    <div class="data-controls">
      <el-card shadow="hover">
        <template #header>
          <div class="control-header">
            <span>数据筛选</span>
            <div class="control-actions">
              <el-button @click="$emit('refresh')" size="small">
                <el-icon><Refresh /></el-icon>
                刷新数据
              </el-button>
              <el-button type="success" @click="$emit('export')" size="small">
                <el-icon><Download /></el-icon>
                导出报告
              </el-button>
            </div>
          </div>
        </template>
        
        <el-form :inline="true" :model="searchForm" class="search-form">
          <el-form-item label="站点">
            <el-select v-model="searchForm.siteId" placeholder="全部站点" style="width: 140px;" clearable>
              <el-option 
                v-for="site in sites" 
                :key="site.id" 
                :label="site.name" 
                :value="site.id" 
              />
            </el-select>
          </el-form-item>
          <el-form-item label="时间范围">
            <el-date-picker
              v-model="searchForm.dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              style="width: 240px;"
            />
          </el-form-item>
          <el-form-item label="操作类型">
            <el-select v-model="searchForm.action" placeholder="全部操作" style="width: 140px;" clearable>
              <el-option label="展示" value="show" />
              <el-option label="点击" value="click" />
              <el-option label="转化" value="convert" />
              <el-option label="关闭" value="close" />
            </el-select>
          </el-form-item>
          <el-form-item label="设备类型">
            <el-select v-model="searchForm.deviceType" placeholder="全部设备" style="width: 140px;" clearable>
              <el-option label="桌面端" value="desktop" />
              <el-option label="移动端" value="mobile" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch" size="small">搜索</el-button>
            <el-button @click="resetSearch" size="small">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>

    <!-- 详细数据表格 -->
    <div class="data-table">
      <el-card shadow="hover">
        <template #header>
          <div class="table-header">
            <span>详细数据记录</span>
            <div class="table-info">
              共 {{ total }} 条记录
            </div>
          </div>
        </template>
        
        <el-table 
          :data="filteredRecords" 
          border 
          style="width: 100%"
          v-loading="loading"
          empty-text="暂无记录数据"
          size="small"
        >
          <el-table-column prop="siteName" label="站点" width="100" />
          <el-table-column prop="popupName" label="弹窗名称" min-width="120" />
          <el-table-column prop="action" label="操作" width="80">
            <template #default="scope">
              <el-tag :type="getActionTagType(scope.row.action)" size="small">
                {{ getActionText(scope.row.action) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="deviceType" label="设备" width="80">
            <template #default="scope">
              <el-tag :type="getDeviceTypeTagType(scope.row.deviceType)" size="small">
                {{ getDeviceTypeText(scope.row.deviceType) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="showTime" label="展示时间" width="140" />
          <el-table-column prop="closeTime" label="关闭时间" width="140" />
          <el-table-column label="转化数据" width="180">
            <template #default="scope">
              <div v-if="scope.row.conversionData" class="conversion-data">
                <div class="conversion-item">
                  <span class="label">订单:</span>
                  <span class="value">{{ scope.row.conversionData.orderId }}</span>
                </div>
                <div class="conversion-item">
                  <span class="label">金额:</span>
                  <span class="value">¥{{ scope.row.conversionData.amount?.toLocaleString() }}</span>
                </div>
                <div class="conversion-item">
                  <span class="label">优惠券:</span>
                  <span class="value">{{ scope.row.conversionData.couponUsed }}</span>
                </div>
              </div>
              <span v-else class="no-data">-</span>
            </template>
          </el-table-column>
          <el-table-column prop="ipAddress" label="IP地址" width="120" />
        </el-table>

        <!-- 分页 -->
        <div class="pagination-area">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            size="small"
          />
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted } from 'vue'
import { Refresh, Download, View, Mouse, ShoppingCart, DataAnalysis } from '@element-plus/icons-vue'
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { BarChart, PieChart, LineChart } from 'echarts/charts'
import {
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent
} from 'echarts/components'
import VChart from 'vue-echarts'
import type { Site, PopupRecord, PopupStats, PopupStyle } from '@/types/sitePopup'

// 注册 ECharts 组件
use([
  CanvasRenderer,
  BarChart,
  PieChart,
  LineChart,
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent
])

// Props
interface Props {
  sites: Site[]
  records: PopupRecord[]
  stats: PopupStats[]
  loading: boolean
}

const props = defineProps<Props>()

// Emits
const emit = defineEmits<{
  refresh: []
  export: []
}>()

// 响应式数据
const searchForm = ref({
  siteId: '',
  action: '',
  deviceType: '',
  dateRange: null as [string, string] | null
})

const currentPage = ref(1)
const pageSize = ref(20)
const total = ref(0)
const selectedPeriod = ref('2024-01')
const trendPeriod = ref('7')

// 图表配置
const barChartOption = ref({
  title: {
    text: '各站点弹窗展示统计',
    left: 'center',
    textStyle: {
      fontSize: 14,
      fontWeight: 'normal'
    }
  },
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'shadow'
    }
  },
  legend: {
    data: ['展示次数', '点击次数', '转化次数'],
    bottom: 10
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '15%',
    top: '15%',
    containLabel: true
  },
  xAxis: {
    type: 'category',
    data: ['煤炉', '雅虎日拍', '雅虎闲置', 'Bookoff']
  },
  yAxis: {
    type: 'value'
  },
  series: [
    {
      name: '展示次数',
      type: 'bar',
      data: [120, 200, 150, 80],
      itemStyle: { color: '#409EFF' }
    },
    {
      name: '点击次数',
      type: 'bar',
      data: [20, 35, 25, 15],
      itemStyle: { color: '#67C23A' }
    },
    {
      name: '转化次数',
      type: 'bar',
      data: [8, 12, 10, 5],
      itemStyle: { color: '#E6A23C' }
    }
  ]
})

const pieChartOption = ref({
  title: {
    text: '弹窗转化率分析',
    left: 'center',
    textStyle: {
      fontSize: 14,
      fontWeight: 'normal'
    }
  },
  tooltip: {
    trigger: 'item',
    formatter: '{a} <br/>{b}: {c} ({d}%)'
  },
  legend: {
    orient: 'vertical',
    left: 'left',
    bottom: 10
  },
  series: [
    {
      name: '弹窗操作',
      type: 'pie',
      radius: ['40%', '70%'],
      avoidLabelOverlap: false,
      label: {
        show: false,
        position: 'center'
      },
      emphasis: {
        label: {
          show: true,
          fontSize: '18',
          fontWeight: 'bold'
        }
      },
      labelLine: {
        show: false
      },
      data: [
        { value: 550, name: '展示', itemStyle: { color: '#409EFF' } },
        { value: 95, name: '点击', itemStyle: { color: '#67C23A' } },
        { value: 35, name: '转化', itemStyle: { color: '#E6A23C' } },
        { value: 420, name: '关闭', itemStyle: { color: '#F56C6C' } }
      ]
    }
  ]
})

const lineChartOption = ref({
  title: {
    text: '弹窗展示趋势',
    left: 'center',
    textStyle: {
      fontSize: 14,
      fontWeight: 'normal'
    }
  },
  tooltip: {
    trigger: 'axis'
  },
  legend: {
    data: ['展示次数', '点击次数', '转化次数'],
    bottom: 10
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '15%',
    top: '15%',
    containLabel: true
  },
  xAxis: {
    type: 'category',
    boundaryGap: false,
    data: ['1月1日', '1月2日', '1月3日', '1月4日', '1月5日', '1月6日', '1月7日']
  },
  yAxis: {
    type: 'value'
  },
  series: [
    {
      name: '展示次数',
      type: 'line',
      stack: 'Total',
      data: [120, 132, 101, 134, 90, 230, 210],
      itemStyle: { color: '#409EFF' }
    },
    {
      name: '点击次数',
      type: 'line',
      stack: 'Total',
      data: [20, 25, 18, 22, 15, 35, 30],
      itemStyle: { color: '#67C23A' }
    },
    {
      name: '转化次数',
      type: 'line',
      stack: 'Total',
      data: [8, 10, 7, 9, 6, 12, 11],
      itemStyle: { color: '#E6A23C' }
    }
  ]
})

// 模拟弹窗样式数据用于搜索
const popupStyles = ref<PopupStyle[]>([])

// 计算属性
const overviewStats = computed(() => {
  const totalShows = props.stats.reduce((sum, stat) => sum + stat.totalShows, 0)
  const totalClicks = props.stats.reduce((sum, stat) => sum + stat.totalClicks, 0)
  const totalConversions = props.stats.reduce((sum, stat) => sum + stat.totalConversions, 0)
  const avgClickRate = props.stats.length > 0 
    ? props.stats.reduce((sum, stat) => sum + stat.clickRate, 0) / props.stats.length 
    : 0

  return [
    {
      label: '总展示次数',
      value: totalShows.toLocaleString(),
      icon: 'View',
      color: '#409eff',
      trend: 12.5
    },
    {
      label: '总点击次数',
      value: totalClicks.toLocaleString(),
      icon: 'Mouse',
      color: '#67c23a',
      trend: 8.3
    },
    {
      label: '总转化次数',
      value: totalConversions.toLocaleString(),
      icon: 'ShoppingCart',
      color: '#e6a23c',
      trend: -2.1
    },
    {
      label: '平均点击率',
      value: avgClickRate.toFixed(2) + '%',
      icon: 'DataAnalysis',
      color: '#f56c6c',
      trend: 5.7
    }
  ]
})

// 漏斗图配置
const funnelChartOption = ref({
  title: {
    text: '用户行为漏斗',
    left: 'center',
    textStyle: {
      fontSize: 14,
      fontWeight: 'normal'
    }
  },
  tooltip: {
    trigger: 'item',
    formatter: '{a} <br/>{b}: {c} ({d}%)'
  },
  legend: {
    data: ['弹窗展示', '用户点击', '用户转化'],
    bottom: 10
  },
  series: [
    {
      name: '用户行为',
      type: 'funnel',
      left: '10%',
      top: 60,
      width: '80%',
      height: '80%',
      min: 0,
      max: 1000,
      minSize: '0%',
      maxSize: '100%',
      sort: 'descending',
      gap: 2,
      label: {
        show: true,
        position: 'inside'
      },
      labelLine: {
        length: 10,
        lineStyle: {
          width: 1,
          type: 'solid'
        }
      },
      itemStyle: {
        borderColor: '#fff',
        borderWidth: 1
      },
      emphasis: {
        label: {
          fontSize: 20
        }
      },
      data: [
        { value: 1000, name: '弹窗展示', itemStyle: { color: '#409EFF' } },
        { value: 200, name: '用户点击', itemStyle: { color: '#67C23A' } },
        { value: 50, name: '用户转化', itemStyle: { color: '#E6A23C' } }
      ]
    }
  ]
})

const filteredRecords = computed(() => {
  let result = [...props.records]
  
  if (searchForm.value.siteId) {
    result = result.filter(item => item.siteId === searchForm.value.siteId)
  }
  
  if (searchForm.value.action) {
    result = result.filter(item => item.action === searchForm.value.action)
  }
  
  if (searchForm.value.deviceType) {
    result = result.filter(item => item.deviceType === searchForm.value.deviceType)
  }
  
  if (searchForm.value.dateRange && searchForm.value.dateRange.length === 2) {
    const [startDate, endDate] = searchForm.value.dateRange
    result = result.filter(item => {
      const itemDate = new Date(item.showTime)
      return itemDate >= new Date(startDate) && itemDate <= new Date(endDate)
    })
  }
  
  total.value = result.length
  
  // 分页处理
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return result.slice(start, end)
})

// 监听记录数据变化
watch(() => props.records, () => {
  total.value = props.records.length
  currentPage.value = 1
}, { immediate: true })

// 方法
const handleSearch = () => {
  currentPage.value = 1
}

const resetSearch = () => {
  searchForm.value = {
    siteId: '',
    action: '',
    deviceType: '',
    dateRange: null
  }
  currentPage.value = 1
}

const handleSizeChange = (size: number) => {
  pageSize.value = size
  currentPage.value = 1
}

const handleCurrentChange = (page: number) => {
  currentPage.value = page
}

const getActionTagType = (action: string) => {
  const actionMap: Record<string, string> = {
    'show': 'info',
    'close': 'warning',
    'click': 'success',
    'convert': 'danger'
  }
  return actionMap[action] || 'info'
}

const getActionText = (action: string) => {
  const actionMap: Record<string, string> = {
    'show': '展示',
    'close': '关闭',
    'click': '点击',
    'convert': '转化'
  }
  return actionMap[action] || action
}

const getDeviceTypeTagType = (type: string) => {
  const typeMap: Record<string, string> = {
    'desktop': 'primary',
    'mobile': 'success'
  }
  return typeMap[type] || 'info'
}

const getDeviceTypeText = (type: string) => {
  const typeMap: Record<string, string> = {
    'desktop': '桌面端',
    'mobile': '移动端'
  }
  return typeMap[type] || type
}

// 图表更新函数
const updateCharts = () => {
  // 根据选择的周期更新图表数据
  console.log('更新图表，周期:', selectedPeriod.value)
  // 这里可以调用API获取对应周期的数据
}

const updateTrendChart = () => {
  // 根据选择的时间范围更新趋势图
  console.log('更新趋势图，时间范围:', trendPeriod.value)
  // 这里可以调用API获取对应时间范围的数据
}
</script>

<style scoped>
.popup-stats-tab {
  padding: 20px;
}

.stats-overview {
  margin-bottom: 20px;
}

.stat-card {
  border-radius: 8px;
}

.stat-content {
  display: flex;
  align-items: center;
  gap: 16px;
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}

.stat-info {
  flex: 1;
}

.stat-value {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 14px;
  color: #909399;
}

.stat-trend {
  display: flex;
  align-items: center;
  margin-top: 8px;
  font-size: 12px;
  color: #909399;
}

.trend-up {
  color: #67C23A;
}

.trend-down {
  color: #F56C6C;
}

.trend-text {
  margin-left: 4px;
}

.main-charts {
  margin-bottom: 20px;
}

.chart-card {
  border-radius: 8px;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chart-controls {
  margin-left: 10px;
}

.chart-container {
  height: 300px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.large {
  height: 300px;
}

.medium {
  height: 300px;
}

.chart {
  width: 100%;
  height: 100%;
}

.chart-placeholder {
  text-align: center;
  color: #909399;
}

.chart-desc {
  font-size: 12px;
  margin-top: 8px;
}

.detail-charts {
  margin-bottom: 20px;
}

.data-controls {
  margin-bottom: 20px;
}

.control-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.control-actions {
  display: flex;
  gap: 12px;
}

.search-form {
  margin: 0;
}

.data-table {
  margin-bottom: 20px;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.table-info {
  font-size: 12px;
  color: #909399;
}

.conversion-data {
  font-size: 12px;
  line-height: 1.4;
}

.conversion-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 2px;
}

.conversion-item .label {
  font-weight: 600;
  color: #606266;
}

.conversion-item .value {
  font-weight: 600;
  color: #303133;
}

.no-data {
  color: #909399;
}

:deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;
}

:deep(.el-table th) {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: 600;
}

:deep(.el-table td) {
  padding: 12px 0;
}

:deep(.el-card__header) {
  padding: 16px 20px;
  border-bottom: 1px solid #e4e7ed;
}

:deep(.el-card__body) {
  padding: 20px;
}
</style>
